package lvbu.wang.lvbuoperator.utils;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.dothantech.lpapi.LPAPI;
import com.dothantech.printer.IDzPrinter;
import com.qing.library.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

public class PrintQrCodeProxy {


    public PrintQrCodeProxy(Context context) {
        this.context = context;
        init();
    }

    private LPAPI api;
    private Context context;
    private View.OnClickListener completeLis;

    private List<IDzPrinter.PrinterAddress> pairedPrinters = new ArrayList<>();

    private String txt;

    private void init() {
        this.api = LPAPI.Factory.createInstance(mCallback);
    }

    public void print(String qrcode) {
        this.txt = qrcode;
//        this.completeLis = lis;
        selectPrinterOnClick();
    }

    // 选择打印机的按钮事件
    private void selectPrinterOnClick() {
        BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        if (btAdapter == null) {
            ToastUtil.showShortToast(context, "当前设备不支持蓝牙！");
            return;
        }
        if (!btAdapter.isEnabled()) {
            ToastUtil.showShortToast(context, "蓝牙适配器未开启！");
            return;
        }

        pairedPrinters = api.getAllPrinterAddresses(null);
        new AlertDialog.Builder(context).setTitle("选择已绑定的设备").setAdapter(new DeviceListAdapter(), (dialogInterface, i) -> {
            IDzPrinter.PrinterAddress printer = pairedPrinters.get(i);
            if (printer != null) {
                // 连接选择的打印机
                if (api.openPrinterByAddress(printer)) {
                    // 连接打印机的请求提交成功，刷新界面提示
                    // onPrinterConnecting(printer, true);
                    print2dBarcode();
                }
            }
        }).show();
    }

    // 打印二维码
    private boolean print2dBarcode() {
        // 开始绘图任务，传入参数(页面宽度, 页面高度)
        api.startJob(30, 30, 0);
        // 开始一个页面的绘制，绘制二维码
        // 传入参数(需要绘制的二维码的数据, 绘制的二维码左上角水平位置, 绘制的二维码左上角垂直位置, 绘制的二维码的宽度(宽高相同))
        api.draw2DQRCode(txt, 4, 0, 22);
        api.drawTextRegular(txt,3,23,0,0,3, LPAPI.FontStyle.BOLD);
        // 结束绘图任务提交打印
        return api.commitJob();
    }

    private void quit() {
        api.quit();
    }


    // LPAPI 打印机操作相关的回调函数。
    private final LPAPI.Callback mCallback = new LPAPI.Callback() {

        /****************************************************************************************************************************************/
        // 所有回调函数都是在打印线程中被调用，因此如果需要刷新界面，需要发送消息给界面主线程，以避免互斥等繁琐操作。

        /****************************************************************************************************************************************/

        // 打印机连接状态发生变化时被调用
        @Override
        public void onStateChange(IDzPrinter.PrinterAddress arg0, IDzPrinter.PrinterState arg1) {
            final IDzPrinter.PrinterAddress printer = arg0;
            switch (arg1) {
                case Connected:
                case Connected2:
                    // 打印机连接成功，发送通知，刷新界面提示
//                    print2dBarcode();
                    onPrintSuccess();
                    break;

                case Disconnected:
                    // 打印机连接失败、断开连接，发送通知，刷新界面提示
                    onPrintFailed();
                    break;

                default:
                    break;
            }
        }

        // 蓝牙适配器状态发生变化时被调用
        @Override
        public void onProgressInfo(IDzPrinter.ProgressInfo arg0, Object arg1) {
        }

        @Override
        public void onPrinterDiscovery(IDzPrinter.PrinterAddress arg0, IDzPrinter.PrinterInfo arg1) {
        }

        // 打印标签的进度发生变化是被调用
        @Override
        public void onPrintProgress(IDzPrinter.PrinterAddress address, Object bitmapData, IDzPrinter.PrintProgress progress, Object addiInfo) {
            switch (progress) {
                case Success:
                    // 打印标签成功，发送通知，刷新界面提示
                    onPrintSuccess();
                    complete();
                    break;

                case Failed:
                    // 打印标签失败，发送通知，刷新界面提示
                    onPrintFailed();
                    complete();
                    break;

                default:
                    break;
            }
        }
    };

    private void complete(){
        quit();
        if(completeLis != null) completeLis.onClick(null);
    }

    // 用于填充打印机列表的Adapter
    private class DeviceListAdapter extends BaseAdapter {
        private TextView tv_name = null;

        @Override
        public int getCount() {
            return pairedPrinters.size();
        }

        @Override
        public Object getItem(int position) {
            return pairedPrinters.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, null);
            }
            tv_name = (TextView) convertView.findViewById(android.R.id.text1);

            if (pairedPrinters != null && pairedPrinters.size() > position) {
                IDzPrinter.PrinterAddress printer = pairedPrinters.get(position);
//                tv_name.setText(printer.shownName + "\n" + printer.macAddress);
                tv_name.setBackgroundColor(Color.parseColor("#f5f5f5"));
                tv_name.setText(printer.shownName);
                // tv_mac.setText();
            }

            return convertView;
        }
    }

    private void onPrintSuccess() {
//        ToastUtil.showShortToast(context,"打印成功");
    }

    private void onPrintFailed() {
//        ToastUtil.showShortToast(context,"打印失败");
    }

}
